package io.hepu.robotize.util;

import javax.annotation.CheckForNull;
import java.util.Collections;
import java.util.List;

public final class Strings {

    public static final String EMPTY = "";
    public static final String COLON = ":";

    private Strings() {
    }

    public static boolean nonEmpty(String string) {
        return string != null && !string.isEmpty();
    }

    public static boolean isEmpty(String string) {
        return string == null || string.isEmpty();
    }

    public static boolean nonBlank(String string) {
        return !isEmpty(string);
    }

    public static String toString(Object object) {
        return object != null ? String.valueOf(object) : null;
    }

    public static <T> String toString(T[] objects) {
        StringBuilder builder = new StringBuilder();
        for (T object : objects) {
            builder.append(object);
        }
        return builder.toString();
    }

    /**
     * Turn the first letter to Lower
     */
    public static String firstLower(String string) {
        char first = string.charAt(0);
        String temp = String.valueOf(first);
        if (first >= 'A' && first <= 'Z') {
            string = string.replaceFirst(temp, temp.toLowerCase());
        }
        return string;
    }

    /**
     * Turn the first letter to Upper
     */
    public static String firstUpper(String string) {
        char first = string.charAt(0);
        String temp = String.valueOf(first);
        if (first >= 'a' && first <= 'z') {
            string = string.replaceFirst(temp, temp.toUpperCase());
        }
        return string;
    }

    /**
     * Eliminate blank contents in the list.
     *
     * @param list Target list to eliminate.
     * @return List<T>
     */
    public static List<String> trim(List<String> list) {
        return JCollection.eliminate(list, Collections.singleton(EMPTY));
    }

    public static String trim(Object object, String target) {
        return String.valueOf(object).replace(target, EMPTY);
    }

    public static String[] split(String string) {
        return split(string, COLON);
    }

    public static String[] split(String string, String regex) {
        return Limits.nonEmpty(string) ? string.split(regex) : new String[0];
    }

    /**
     * Returns the string if it is not null, or an empty string otherwise.
     *
     * @param string the string to test and possibly return
     * @return {@code string} if it is not null; {@code ""} otherwise
     */
    public static String nullToEmpty(@CheckForNull String string) {
        return (string == null) ? "" : string;
    }

    /**
     * Returns the string if it is not empty, or a null string otherwise.
     *
     * @param string the string to test and possibly return
     * @return {@code string} if it is not empty; {@code null} otherwise
     */
    @CheckForNull
    public static String emptyToNull(@CheckForNull String string) {
        return isEmpty(string) ? null : string;
    }
}
